package com.ccl.iot.publics;import java.util.ArrayList;

public abstract class ListenerHolder<LISTENER, OBJECT> {
	private ArrayList<LISTENER> iListeners = null;
	
	public int getListenerCount(){
		return iListeners != null ? iListeners.size() : 0;
	}
	
	public boolean addListener(LISTENER aListener){
		if (aListener != null){
			if (iListeners == null){
				iListeners = new ArrayList<LISTENER>();
			}else{
				synchronized(this){
					if (iListeners.contains(aListener)){
						return false;
					}
				}
			}
			
			return iListeners.add(aListener);
		}
		
		return false;
	}
	
	public boolean removeListener(LISTENER aListener){
		if (aListener != null && iListeners != null){
			synchronized(iListeners){
				return iListeners.remove(aListener);
			}
		}
		
		return false;
	}
	
	protected abstract void onCall(LISTENER aListener, int aID, OBJECT aObject);
	
	public void call(int aID, OBJECT aObject){
		if (iListeners != null){
			synchronized(iListeners){
				for (int i = 0, tCount = iListeners.size(); i < tCount; i++){
					onCall(iListeners.get(i), aID, aObject);
				}
			}
		}
	}
}
